//
//  BDtakeLetterVideoViewController.m
//  BadBoy
//
//  Created by wen on 2017/6/13.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDtakeLetterVideoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "HAVPlayer.h"
#import "HProgressView.h"
#import <AssetsLibrary/AssetsLibrary.h>

typedef void(^PropertyChangeBlock)(AVCaptureDevice *captureDevice);
@interface BDtakeLetterVideoViewController ()<AVCaptureFileOutputRecordingDelegate>

//轻触拍照，按住摄像
@property (strong, nonatomic) UILabel *labelTipTitle;

//视频输出流
@property (strong,nonatomic) AVCaptureMovieFileOutput *captureMovieFileOutput;
//图片输出流
//@property (strong,nonatomic) AVCaptureStillImageOutput *captureStillImageOutput;//照片输出流
//负责从AVCaptureDevice获得输入数据
@property (strong,nonatomic) AVCaptureDeviceInput *captureDeviceInput;

@property (strong, nonatomic) UIImageView *focusCursor; //聚焦光标

//负责输入和输出设备之间的数据传递
@property(nonatomic)AVCaptureSession *session;

//图像预览层，实时显示捕获的图像
@property(nonatomic)AVCaptureVideoPreviewLayer *previewLayer;

@property (strong, nonatomic) UIButton *btnBack;
//重新录制
@property (strong, nonatomic) UIButton *btnAfresh;
//确定
@property (strong, nonatomic) UIButton *btnEnsure;
//摄像头切换
@property (strong, nonatomic) UIButton *btnCamera;

@property (strong, nonatomic) UIImageView *bgView;
//记录录制的时间 默认最大60秒
@property (assign, nonatomic) CGFloat seconds;

//记录需要保存视频的路径
@property (strong, nonatomic) NSURL *saveVideoUrl;

//是否在对焦
@property (assign, nonatomic) BOOL isFocus;

//视频播放
@property (strong, nonatomic) HAVPlayer *player;

@property (strong, nonatomic) HProgressView *progressView;

//是否是摄像 YES 代表是录制  NO 表示拍照
@property (assign, nonatomic) BOOL isVideo;

@property (strong, nonatomic) UIImage *takeImage;
@property (strong, nonatomic) UIImageView *takeImageView;
@property (strong, nonatomic) UIButton *btnRecord;

//@property (strong, nonatomic) NSTimer *timer;
@property (assign, nonatomic) BOOL startRecord;
@end

//时间大于这个就是视频，否则为拍照
#define TimeMax 1

@implementation BDtakeLetterVideoViewController

-(void)dealloc{
    [self removeNotification];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    if (self.HSeconds == 0) {
        self.HSeconds = 60;
    }
    
    self.btnRecord.hidden = NO;
    self.btnBack.hidden = NO;
    self.btnCamera.hidden = NO;
    self.btnAfresh.hidden = YES;
    self.btnEnsure.hidden = YES;
    self.labelTipTitle.hidden = NO;
    
    [self binRAC];
}

- (void)hiddenTipsLabel {
    self.labelTipTitle.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    [self customCamera];
    [self.session startRunning];
}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.session stopRunning];
    [self.player stopPlayer];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

- (void)customCamera {
    
    //初始化会话，用来结合输入输出
    self.session = [[AVCaptureSession alloc] init];
    //设置分辨率 (设备支持的最高分辨率)
    if ([self.session canSetSessionPreset:AVCaptureSessionPresetHigh]) {
        self.session.sessionPreset = AVCaptureSessionPresetHigh;
    }
    //取得后置摄像头
    AVCaptureDevice *captureDevice = [self getCameraDeviceWithPosition:AVCaptureDevicePositionBack];
    //添加一个音频输入设备
    AVCaptureDevice *audioCaptureDevice=[[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject];
    
    //初始化输入设备
    NSError *error = nil;
    self.captureDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:captureDevice error:&error];
    if (error) {
        // BDLog(ASLocalizedString(@"取得设备输入对象时出错，错误原因：%@"),error.localizedDescription);
        return;
    }
    
    //添加音频
    error = nil;
    AVCaptureDeviceInput *audioCaptureDeviceInput=[[AVCaptureDeviceInput alloc]initWithDevice:audioCaptureDevice error:&error];
    if (error) {
        return;
    }
    
    //输出对象
    self.captureMovieFileOutput = [[AVCaptureMovieFileOutput alloc] init];//视频输出
    
    //将输入设备添加到会话
    if ([self.session canAddInput:self.captureDeviceInput]) {
        [self.session addInput:self.captureDeviceInput];
        [self.session addInput:audioCaptureDeviceInput];
        //设置视频防抖
        AVCaptureConnection *connection = [self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
        if ([connection isVideoStabilizationSupported]) {
            connection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeCinematic;
        }
    }
    
    //将输出设备添加到会话 (刚开始 是照片为输出对象)
    if ([self.session canAddOutput:self.captureMovieFileOutput]) {
        [self.session addOutput:self.captureMovieFileOutput];
    }
    
    //创建视频预览层，用于实时展示摄像头状态
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.frame = self.view.bounds;//CGRectMake(0, 0, self.view.width, self.view.height);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;//填充模式
    [self.bgView.layer addSublayer:self.previewLayer];
    
    [self addNotificationToCaptureDevice:captureDevice];
    [self addGenstureRecognizer];
}

- (void)binRAC{
    [[self.btnBack rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self dismissViewControllerAnimated:YES completion:^{
            //        [Utility hideProgressDialog];
        }];
    }];
    
    [[self.btnAfresh rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        // BDLog(ASLocalizedString(@"重新录制"));
        [self recoverLayout];
    }];
    
    [[self.btnEnsure rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        // BDLog(ASLocalizedString(@"确定 这里进行保存或者发送出去"));
        if (self.saveVideoUrl) {
            if (self.takeBlock) {
                self.takeBlock(self.saveVideoUrl);
            }
        } else {
            //照片
            UIImageWriteToSavedPhotosAlbum(self.takeImage, self, nil, nil);
            if (self.takeBlock) {
                self.takeBlock(self.takeImage);
            }
        }
        [self.btnBack sendActionsForControlEvents:UIControlEventTouchUpInside];
    }];
    
    [[self.btnCamera rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        // BDLog(ASLocalizedString(@"切换摄像头"));
        AVCaptureDevice *currentDevice=[self.captureDeviceInput device];
        AVCaptureDevicePosition currentPosition=[currentDevice position];
        [self removeNotificationFromCaptureDevice:currentDevice];
        AVCaptureDevice *toChangeDevice;
        AVCaptureDevicePosition toChangePosition = AVCaptureDevicePositionFront;//前
        if (currentPosition == AVCaptureDevicePositionUnspecified || currentPosition == AVCaptureDevicePositionFront) {
            toChangePosition = AVCaptureDevicePositionBack;//后
        }
        toChangeDevice=[self getCameraDeviceWithPosition:toChangePosition];
        [self addNotificationToCaptureDevice:toChangeDevice];
        //获得要调整的设备输入对象
        AVCaptureDeviceInput *toChangeDeviceInput=[[AVCaptureDeviceInput alloc]initWithDevice:toChangeDevice error:nil];
        
        //改变会话的配置前一定要先开启配置，配置完成后提交配置改变
        [self.session beginConfiguration];
        //移除原有输入对象
        [self.session removeInput:self.captureDeviceInput];
        //添加新的输入对象
        if ([self.session canAddInput:toChangeDeviceInput]) {
            [self.session addInput:toChangeDeviceInput];
            self.captureDeviceInput = toChangeDeviceInput;
        }
        //提交会话配置
        [self.session commitConfiguration];
    }];
    
    [[self.btnRecord rac_signalForControlEvents:UIControlEventTouchDown] subscribeNext:^(__kindof UIControl * _Nullable x) {
        // BDLog(ASLocalizedString(@"点击了录制按钮"));
        self.progressView.hidden = NO;
        self.progressView.progressValue = 0;
        self.seconds = 0;
        //根据设备输出获得连接
        AVCaptureConnection *connection = [self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeAudio];
        //根据连接取得设备输出的数据
        if (![self.captureMovieFileOutput isRecording]) {
            if (self.saveVideoUrl) {
                [[NSFileManager defaultManager] removeItemAtURL:self.saveVideoUrl error:nil];
            }
            //预览图层和视频方向保持一致
            connection.videoOrientation = [self.previewLayer connection].videoOrientation;
            NSString *outputFielPath=[NSTemporaryDirectory() stringByAppendingString:@"myMovie.MOV"];
            //            NSLog(@"save path is :%@",outputFielPath);
            NSURL *fileUrl=[NSURL fileURLWithPath:outputFielPath];
            //            NSLog(@"fileUrl:%@",fileUrl);
            [self.captureMovieFileOutput startRecordingToOutputFileURL:fileUrl recordingDelegate:self];
        }
    }];
    
    [[self.btnRecord rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        // BDLog(ASLocalizedString(@"录制按钮抬起"));
        [self willEndRecord];
    }];
    
    [[self.btnRecord rac_signalForControlEvents:UIControlEventTouchDragExit] subscribeNext:^(__kindof UIControl * _Nullable x) {
        // BDLog(ASLocalizedString(@"录制按钮触摸到范围外"));
        [self willEndRecord];
    }];
}

- (void)willEndRecord{
    // BDLog(ASLocalizedString(@"当前的时间：%@"), @(self.seconds));
    if (self.seconds >= 0.2) {
        // BDLog(ASLocalizedString(@"当前时间大于0.2走了这里"));
        [self endRecord];
    }else{
        // BDLog(ASLocalizedString(@"当前时间小于0.2走了这里"));
        [self performSelector:@selector(willEndRecord) withObject:nil afterDelay:0.1];
    }
}

- (void)endRecord {
    // BDLog(ASLocalizedString(@"开始调用停止录制"));
    [self.captureMovieFileOutput stopRecording];//停止录制
}

- (void)onStartTranscribe {
    if (self.startRecord == YES && self.seconds < self.HSeconds) {
        self.isVideo = YES;//长按时间超过TimeMax 表示是视频录制
        self.progressView.progressValue = self.seconds / self.HSeconds;
        self.seconds += 0.1;
        [self performSelector:@selector(onStartTranscribe) withObject:nil afterDelay:0.1];
    }else{
        if ([self.captureMovieFileOutput isRecording]) {
            [self.captureMovieFileOutput stopRecording];
        }
    }
}


#pragma mark - 视频输出代理
-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections{
    // BDLog(ASLocalizedString(@"开始录制..."));
    self.startRecord = YES;
    [self onStartTranscribe];
}
-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error{
    // BDLog(ASLocalizedString(@"视频录制完成."));
    self.startRecord = NO;
    [self performSelector:@selector(finishRecordWithFileURL:) withObject:outputFileURL afterDelay:0.1];
}

- (void)finishRecordWithFileURL:(NSURL *)outputFileURL{
    [self changeLayout];
    //    if (self.isVideo) {
    self.saveVideoUrl = outputFileURL;
    // BDLog(ASLocalizedString(@"当前录制视频的时长是:%@"), @(self.seconds));
    if (!self.player) {
        self.player = [[HAVPlayer alloc] initWithFrame:self.bgView.bounds withShowInView:self.bgView url:outputFileURL];
    } else {
        if (outputFileURL) {
            self.player.videoUrl = outputFileURL;
            self.player.hidden = NO;
        }
    }
    //    } else {
    //        //照片
    //        self.saveVideoUrl = nil;
    //        [self videoHandlePhoto:outputFileURL];
    //    }
}

- (void)videoHandlePhoto:(NSURL *)url {
    AVURLAsset *urlSet = [AVURLAsset assetWithURL:url];
    AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlSet];
    imageGenerator.appliesPreferredTrackTransform = YES;    // 截图的时候调整到正确的方向
    NSError *error = nil;
    CMTime time = CMTimeMake(0,30);//缩略图创建时间 CMTime是表示电影时间信息的结构体，第一个参数表示是视频第几秒，第二个参数表示每秒帧数.(如果要获取某一秒的第几帧可以使用CMTimeMake方法)
    CMTime actucalTime; //缩略图实际生成的时间
    CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time actualTime:&actucalTime error:&error];
    if (error) {
        // BDLog(ASLocalizedString(@"截取视频图片失败:%@"),error.localizedDescription);
    }
    CMTimeShow(actucalTime);
    UIImage *image = [UIImage imageWithCGImage:cgImage];
    
    CGImageRelease(cgImage);
    if (image) {
        // BDLog(ASLocalizedString(@"视频截取成功"));
    } else {
        // BDLog(ASLocalizedString(@"视频截取失败"));
    }
    
    
    self.takeImage = image;//[UIImage imageWithCGImage:cgImage];
    
    [[NSFileManager defaultManager] removeItemAtURL:url error:nil];
    
    if (!self.takeImageView) {
        self.takeImageView = [[UIImageView alloc] initWithFrame:self.view.frame];
        [self.bgView addSubview:self.takeImageView];
    }
    self.takeImageView.hidden = NO;
    self.takeImageView.image = self.takeImage;
}

#pragma mark - 通知

//注册通知
- (void)setupObservers
{
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationWillResignActiveNotification object:[UIApplication sharedApplication]];
}

//进入后台就退出视频录制
- (void)applicationDidEnterBackground:(NSNotification *)notification {
    [self.btnBack sendActionsForControlEvents:UIControlEventTouchUpInside];
}

/**
 *  给输入设备添加通知
 */
-(void)addNotificationToCaptureDevice:(AVCaptureDevice *)captureDevice{
    //注意添加区域改变捕获通知必须首先设置设备允许捕获
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        captureDevice.subjectAreaChangeMonitoringEnabled=YES;
    }];
    NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter];
    //捕获区域发生改变
    [notificationCenter addObserver:self selector:@selector(areaChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:captureDevice];
}
-(void)removeNotificationFromCaptureDevice:(AVCaptureDevice *)captureDevice{
    NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:captureDevice];
}
/**
 *  移除所有通知
 */
-(void)removeNotification{
    NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self];
}

-(void)addNotificationToCaptureSession:(AVCaptureSession *)captureSession{
    NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter];
    //会话出错
    [notificationCenter addObserver:self selector:@selector(sessionRuntimeError:) name:AVCaptureSessionRuntimeErrorNotification object:captureSession];
}

/**
 *  设备连接成功
 *
 *  @param notification 通知对象
 */
-(void)deviceConnected:(NSNotification *)notification{
//    NSLog(ASLocalizedString(@"设备已连接..."));
}
/**
 *  设备连接断开
 *
 *  @param notification 通知对象
 */
-(void)deviceDisconnected:(NSNotification *)notification{
//    NSLog(ASLocalizedString(@"设备已断开."));
}
/**
 *  捕获区域改变
 *
 *  @param notification 通知对象
 */
-(void)areaChange:(NSNotification *)notification{
//    NSLog(ASLocalizedString(@"捕获区域改变..."));
}

/**
 *  会话出错
 *
 *  @param notification 通知对象
 */
-(void)sessionRuntimeError:(NSNotification *)notification{
//    NSLog(ASLocalizedString(@"会话发生错误."));
}



/**
 *  取得指定位置的摄像头
 *
 *  @param position 摄像头位置
 *
 *  @return 摄像头设备
 */
-(AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition )position{
    NSArray *cameras= [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *camera in cameras) {
        if ([camera position] == position) {
            return camera;
        }
    }
    return nil;
}

/**
 *  改变设备属性的统一操作方法
 *
 *  @param propertyChange 属性改变操作
 */
-(void)changeDeviceProperty:(PropertyChangeBlock)propertyChange{
    AVCaptureDevice *captureDevice= [self.captureDeviceInput device];
    NSError *error;
    //注意改变设备属性前一定要首先调用lockForConfiguration:调用完之后使用unlockForConfiguration方法解锁
    if ([captureDevice lockForConfiguration:&error]) {
        //自动白平衡
        if ([captureDevice isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]) {
            [captureDevice setWhiteBalanceMode:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance];
        }
        //自动根据环境条件开启闪光灯
        if ([captureDevice isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [captureDevice setFlashMode:AVCaptureFlashModeAuto];
        }
        
        propertyChange(captureDevice);
        [captureDevice unlockForConfiguration];
    }else{
//        NSLog(ASLocalizedString(@"设置设备属性过程发生错误，错误信息：%@"),error.localizedDescription);
    }
}

/**
 *  设置闪光灯模式
 *
 *  @param flashMode 闪光灯模式
 */
-(void)setFlashMode:(AVCaptureFlashMode )flashMode{
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isFlashModeSupported:flashMode]) {
            [captureDevice setFlashMode:flashMode];
        }
    }];
}
/**
 *  设置聚焦模式
 *
 *  @param focusMode 聚焦模式
 */
-(void)setFocusMode:(AVCaptureFocusMode )focusMode{
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isFocusModeSupported:focusMode]) {
            [captureDevice setFocusMode:focusMode];
        }
    }];
}
/**
 *  设置曝光模式
 *
 *  @param exposureMode 曝光模式
 */
-(void)setExposureMode:(AVCaptureExposureMode)exposureMode{
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isExposureModeSupported:exposureMode]) {
            [captureDevice setExposureMode:exposureMode];
        }
    }];
}
/**
 *  设置聚焦点
 *
 *  @param point 聚焦点
 */
-(void)focusWithMode:(AVCaptureFocusMode)focusMode exposureMode:(AVCaptureExposureMode)exposureMode atPoint:(CGPoint)point{
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isExposureModeSupported:exposureMode]) {
            [captureDevice setExposureMode:exposureMode];
        }
        if ([captureDevice isFocusModeSupported:focusMode]) {
            [captureDevice setFocusMode:focusMode];
        }
    }];
}

/**
 *  添加点按手势，点按时聚焦
 */
-(void)addGenstureRecognizer{
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapScreen:)];
    [self.bgView addGestureRecognizer:tapGesture];
}

-(void)tapScreen:(UITapGestureRecognizer *)tapGesture{
    if ([self.session isRunning]) {
        CGPoint point= [tapGesture locationInView:self.bgView];
        //将UI坐标转化为摄像头坐标
        CGPoint cameraPoint= [self.previewLayer captureDevicePointOfInterestForPoint:point];
        [self setFocusCursorWithPoint:point];
        [self focusWithMode:AVCaptureFocusModeContinuousAutoFocus exposureMode:AVCaptureExposureModeContinuousAutoExposure atPoint:cameraPoint];
    }
}

/**
 *  设置聚焦光标位置
 *
 *  @param point 光标位置
 */
-(void)setFocusCursorWithPoint:(CGPoint)point{
    if (!self.isFocus) {
        self.isFocus = YES;
        self.focusCursor.center=point;
        self.focusCursor.transform = CGAffineTransformMakeScale(1.25, 1.25);
        self.focusCursor.alpha = 1.0;
        [UIView animateWithDuration:0.5 animations:^{
            self.focusCursor.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [self performSelector:@selector(onHiddenFocusCurSorAction) withObject:nil afterDelay:0.5];
        }];
    }
}

- (void)onHiddenFocusCurSorAction {
    self.focusCursor.alpha=0;
    self.isFocus = NO;
}

//拍摄完成时调用
- (void)changeLayout {
    self.labelTipTitle.hidden = YES;
    self.btnRecord.hidden = YES;
    self.btnCamera.hidden = YES;
    self.btnAfresh.hidden = NO;
    self.btnEnsure.hidden = NO;
    self.btnBack.hidden = YES;
    if (self.isVideo) {
        [self.progressView clearProgress];
    }
    
    self.btnAfresh.centerX = kBDScreenWidth / 2.0;
    self.btnEnsure.centerX = kBDScreenWidth / 2.0;
    
    [UIView animateWithDuration:0.25 animations:^{
        self.btnAfresh.left = 33;
        self.btnEnsure.right = kBDScreenWidth - 33;
    }];
    [self.session stopRunning];
}


//重新拍摄时调用
- (void)recoverLayout {
    if (self.isVideo) {
        self.isVideo = NO;
        [self.player stopPlayer];
        self.player.hidden = YES;
    }
    [self.session startRunning];
    
    if (!self.takeImageView.hidden) {
        self.takeImageView.hidden = YES;
    }
    
    self.labelTipTitle.hidden = NO;
    self.btnRecord.hidden = NO;
    self.btnCamera.hidden = NO;
    self.btnAfresh.hidden = YES;
    self.btnEnsure.hidden = YES;
    self.btnBack.hidden = NO;
}

- (UIImageView *)bgView{
    if (!_bgView) {
        self.bgView = [[UIImageView alloc] initWithFrame:self.view.bounds];
        _bgView.userInteractionEnabled = YES;
        [self.view insertSubview:_bgView atIndex:0];
    }
    return _bgView;
}

- (UIButton *)btnCamera{
    if (!_btnCamera) {
        self.btnCamera = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnCamera setImage:[UIImage imageNamed:@"call_shexiangtou"] forState:UIControlStateNormal];
        _btnCamera.size = CGSizeMake(35, 35);
        _btnCamera.right = kBDScreenWidth - 30;
        _btnCamera.top = 50;
        [self.view addSubview:_btnCamera];
    }
    return _btnCamera;
}

- (UIButton *)btnRecord{
    if (!_btnRecord) {
        self.btnRecord = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnRecord setBackgroundImage:[UIImage imageNamed:@"littleVideo_luzhi"] forState:UIControlStateNormal];
        _btnRecord.size = CGSizeMake(84, 84);
        _btnRecord.bottom = kBDScreenHeight - 31;
        _btnRecord.centerX = kBDScreenWidth / 2.0;
        _btnRecord.showsTouchWhenHighlighted = YES;
        _btnRecord.layer.masksToBounds = YES;
        _btnRecord.layer.cornerRadius = _btnRecord.width / 2.0;
        [self.view addSubview:_btnRecord];
    }
    return _btnRecord;
}

- (HProgressView *)progressView{
    if (!_progressView) {
        self.progressView = [[HProgressView alloc] initWithFrame:self.btnRecord.bounds];
        _progressView.layer.cornerRadius = _progressView.width/2;
        _progressView.backgroundColor = [UIColor clearColor];
        _progressView.color = KBDColorBlue;
        _progressView.lineWidth = 10;
        [self.btnRecord addSubview:_progressView];
    }
    return _progressView;
}

- (UIButton *)btnBack{
    if (!_btnBack) {
        self.btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnBack.size = CGSizeMake(20, 20);
        _btnBack.centerY = self.btnRecord.centerY;
        _btnBack.right = self.btnRecord.left - 58;
        [_btnBack setBackgroundImage:[UIImage imageNamed:@"littleVideo_back"] forState:UIControlStateNormal];
        [_btnBack setEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [self.view addSubview:_btnBack];
    }
    return _btnBack;
}

- (UIButton *)btnAfresh{
    if (!_btnAfresh) {
        self.btnAfresh = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnAfresh.size = CGSizeMake(70, 70);
        _btnAfresh.center = self.btnRecord.center;
        [_btnAfresh setBackgroundImage:[UIImage imageNamed:@"littleVideo_quxiao"] forState:UIControlStateNormal];
        [self.view addSubview:_btnAfresh];
    }
    return _btnAfresh;
}

- (UIButton *)btnEnsure{
    if (!_btnEnsure) {
        self.btnEnsure = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnEnsure.size = CGSizeMake(70, 70);
        _btnEnsure.center = self.btnRecord.center;
        [_btnEnsure setBackgroundImage:[UIImage imageNamed:@"littleVideo_queding"] forState:UIControlStateNormal];
        [self.view addSubview:_btnEnsure];
    }
    return _btnEnsure;
}

- (UIImageView *)focusCursor{
    if (!_focusCursor) {
        self.focusCursor = [[UIImageView alloc] init];
        [self.view addSubview:_focusCursor];
    }
    return _focusCursor;
}

- (UILabel *)labelTipTitle{
    if (!_labelTipTitle) {
        self.labelTipTitle = [[UILabel alloc] init];
        _labelTipTitle.text = ASLocalizedString(@"按住开始录制视频，松开结束录制");
        _labelTipTitle.font = [UIFont systemFontOfSize:15];
        _labelTipTitle.textColor = [UIColor whiteColor];
        [_labelTipTitle sizeToFit];
        _labelTipTitle.bottom = self.btnRecord.top - 15;
        _labelTipTitle.centerX = kBDScreenWidth / 2.0;
        [self.view addSubview:_labelTipTitle];
    }
    return _labelTipTitle;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
